package com.kxf.androidtestdemo.activity;

import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.kxf.androidtestdemo.R;

public class HandleTestActivity extends BaseActivity {

    private TextView tv;
    private int id = 0;
    private Handler handlerChild = null;
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Log.e("HandleTestActivity", "handleMessage");
            tv.setText(msg.arg1 + "");
            Toast.makeText(HandleTestActivity.this, msg.arg1 + " handleMessage", Toast.LENGTH_LONG).show();
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.e("HandleTestActivity", "onCreate");
        setContentView(R.layout.activity_handle_test);
        tv = findViewById(R.id.tv);
        Message msg = handler.obtainMessage();
        ++id;
        msg.arg1 = id;
        handler.sendMessageDelayed(msg, 2000);

        //子线程创建handler
        new Thread(new Runnable() {
            @Override
            public void run() {
                Looper.prepare();//华为手机上不调用也不会报错 华为荣耀10，Android10，sdk29
                Log.d(tag, "创建handlerChild " + Build.VERSION.SDK_INT);
                Log.d(tag, "创建handlerChild " + Looper.myLooper());
                handlerChild = new Handler(){
                    @Override
                    public void handleMessage(Message msg) {
                        super.handleMessage(msg);
                        Log.d(tag, "子线程接收到消息");
                    }
                };
                Log.d(tag, "创建handlerChild over " + handlerChild.getLooper());
                Looper.loop();
            }
        }).start();
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.e("HandleTestActivity", "onPause");
//        Message msg = handler.obtainMessage();
//        ++id;
//        msg.arg1 = id;
//        handler.sendMessageDelayed(msg, 100000);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.e("HandleTestActivity", "onDestroy");
        //我们可以在Activity onDestroy()时调用handler.removeCallbacksAndMessages(null)，
        // 这样就把queue里所有的message都remove掉了，之前说过message被message pool回收掉会reset，
        // 因此不会再引用handler，这条引用链就断掉了。
//        handler.removeCallbacksAndMessages(null);
    }

    /**
     * 当垃圾回收确定不再有对对象的引用时，由垃圾回收器对对象调用。
     * 子类重写@code finalize方法以释放系统资源或执行其他清理。
     * @throws Throwable
     */
    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        Log.e("HandleTestActivity", "finalize");
    }

    public void onSendChild(View view) {
        handlerChild.sendEmptyMessage(1);
    }
}
